package com.jblog.common.web;

import static com.jblog.Constants.Encoding.UTF8;
import static com.jblog.Constants.Template.TPL_STYLE_PAGE_CATEGORY;
import static com.jblog.Constants.Template.TPL_SUFFIX;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.common.web.freemarker.exception.ParamsRequiredException;
import com.jblog.common.web.front.URLHelper;
import com.jblog.common.web.front.URLHelper.PageInfo;
import com.jblog.controller.web.SiteUtils;
import com.jblog.core.model.account.Account;
import com.jblog.core.model.site.Site;

import freemarker.core.Environment;
import freemarker.template.AdapterTemplateModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;

/**
 * 前台工具类
 * 
 */
public class FrontUtils {

	public static final String PAGE_NO = "pageNo";

	public static final String COUNT = "count";

	public static final String FIRST = "first";

	public static final String LOCATION = "location";

	public static final String HREF = "href";

	public static final String HREF_FORMER = "hrefFormer";
	
	public static final String HREF_LATTER = "hrefLatter";
	
    public static final String PARAM_PAGE_CSS_CLASS = "cssClass";
	
    public static final String PARAM_STYLE_LIST = "listStyle";
    
    public static final String PARAM_SYS_PAGE = "pageStyle";
    
    public static final String SITE = "site";
    
    public static final String ACCOUNT = "ACCOUNT";
    
    
	/**
     * 页面没有找到
     * 
     * @param request
     * @param response
     * @return 返回“页面没有找到”的模板
     */
	public static String pageNotFound(HttpServletRequest request,
            HttpServletResponse response, Map<String, Object> model) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return "404";
    }
	
	public static void frontData(HttpServletRequest request,
            Map<String, Object> map) {
	    Account account = SiteUtils.getAccount(request);
	    Site site = SiteUtils.getSite(request);
        String location = RequestUtils.getLocation(request);
        frontData(request, map, account, site, location);
    }

    public static void frontData(HttpServletRequest request,
            Map<String, Object> map, Account account, Site site, String location) {
//        map.put(START_TIME, request.getAttribute(START_TIME));
        if (null != account) {
            map.put(ACCOUNT, account);
        }
        map.put(SITE, site);
//        map.put(RES_SYS, request.getContextPath() + RES_PATH);
//        String res = request.getContextPath() + RES_PATH + "/" + site.getPath()
//                + "/" + site.getTplSolution();
//        // res路径需要去除第一个字符'/'
//        map.put(RES_TPL, res.substring(1));
        map.put(LOCATION, location);
    }
    
    public static void frontPageData(HttpServletRequest request,
            Map<String, Object> map) {
        int pageNo = URLHelper.getPageNo(request);
        PageInfo info = URLHelper.getPageInfo(request);
        String href = info.getHref();
        String hrefFormer = info.getHrefFormer();
        String hrefLatter = info.getHrefLatter();
        frontPageData(pageNo, href, hrefFormer, hrefLatter, map);
    }
    
	public static void frontPageData(int pageNo, String href,
			String hrefFormer, String hrefLatter, Map<String, Object> map) {
		map.put(PAGE_NO, pageNo);
		map.put(HREF, href);
		map.put(HREF_FORMER, hrefFormer);
		map.put(HREF_LATTER, hrefLatter);
	}
	
	public static Site site(Environment env)
           throws TemplateModelException {
       TemplateModel model = env.getGlobalVariable(SITE);
       if (model instanceof AdapterTemplateModel) {
           return (Site) ((AdapterTemplateModel) model)
                   .getAdaptedObject(Site.class);
       } else {
           throw new TemplateModelException("'" + SITE
                   + "' not found in DataModel");
       }
    }

	
	public static Integer pageNo(Environment env) throws TemplateException {
		TemplateModel pageNo = env.getGlobalVariable(PAGE_NO);
		if (pageNo instanceof TemplateNumberModel) {
			return ((TemplateNumberModel) pageNo).getAsNumber().intValue();
		} else {
			throw new TemplateModelException("'" + PAGE_NO + "' not found in DataModel.");
		}
	}

	public static Integer first(Map<String, TemplateModel> params)
			throws TemplateException {
		Integer first = DirectiveUtils.getInt(FIRST, params);
		if (first == null || first <= 0) {
			return 0;
		} else {
			return first;
		}
	}

	/**
	 * 标签参数中获得条数。
	 * 
	 * @param params
	 * @return 如果不存在，或者小于等于0，或者大于100则返回100；否则返回条数。
	 * @throws TemplateException
	 */
	public static Integer count(Map<String, TemplateModel> params)
			throws TemplateException {
		Integer count = DirectiveUtils.getInt(COUNT, params);
		if (count == null || count <= 0 || count >= 100) {
			return 100;
		} else {
			return count;
		}
	}
	
	public static Integer start(Map<String, TemplateModel> params,
            Environment env) throws TemplateException {
        return (FrontUtils.pageNo(env) - 1) * count(params);
    }
	
	public static Integer end(Map<String, TemplateModel> params,
	        Environment env) throws TemplateException {
        return count(params);
    }
	
	public static void includePagination(Map<String, TemplateModel> params, Environment env)
            throws TemplateException, IOException {
        String sysPage = DirectiveUtils.getString(PARAM_SYS_PAGE, params);
        if (!StringUtils.isBlank(sysPage)) {
            String tpl = TPL_STYLE_PAGE_CATEGORY + sysPage + TPL_SUFFIX;
            env.include(tpl, UTF8, true);
        } else {
            throw new ParamsRequiredException(PARAM_SYS_PAGE);
        }
    }

}
